/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package android.isisufes.home.map;

import java.io.StringReader;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import org.xml.sax.InputSource;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.isisufes.R;
import android.isisufes.newclasses.User;
import android.isisufes.newclasses.Users;
import android.isisufes.util.ServerCom;
import android.os.Bundle;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

public class ShowArea extends MapActivity{
	private static final long PERIOD = 10000;
	private Projection projection;
	private int lon;
	private int lat;
	private int radius;
	private long idCamp;
	private MapView mapView;
	private MapController mapc;
	private Timer userUpdateTimer;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mapView = new MapView(this, ServerCom.googleMapsKey);
		
		setContentView(mapView);
		mapView.setClickable(true);

		idCamp = this.getIntent().getLongExtra("id",-1);
	    lon = this.getIntent().getIntExtra("lon",-1);
	    lat = this.getIntent().getIntExtra("lat",-1);
	    radius = this.getIntent().getIntExtra("radius", -1);
		/*Log.d("lat, lon e radius",String.valueOf(lat));
		Log.d("lat, lon e radius",String.valueOf(lon));
		Log.d("lat, lon e radius",String.valueOf(radius));
		Log.d("lat, lon e radius",String.valueOf(idCamp));*/
	    GeoPoint point2;
		if(lon == 0 && lat ==0){
			point2 = new GeoPoint(-12211180,-53525395);//Centro do Brasil
		}else{
			point2 = new GeoPoint(lat,lon);
		}
		mapc = mapView.getController();
		mapc.setZoom(5);
		mapc.setCenter(point2);
		mapView.setBuiltInZoomControls(true);
	    
	    Log.d("ShowArea","drawUsers()");
	    
	    radius = constroiRaio();
	    drawUsers();
	    userUpdateTimer = new Timer();
	    userUpdateTimer.scheduleAtFixedRate(new DrawUsersPolling(), PERIOD, PERIOD);
	}
	
	/*Pega a id da campanha atual e retorna o xml com os usuarios*/
	private void drawUsers(){
		
		List<Overlay> mapOverlays = mapView.getOverlays();
		mapOverlays.clear();
		
	    String xml2 = ServerCom.getCampMembers(idCamp);
	    //Log.d("UsersXML",xml2);
	    Vector<User> usu = Users.parse(new InputSource(new StringReader(xml2)));
	    Double la,lo;
	    
	    /*Desenha no mapa as posiçoes*/
	    Drawable drawable = this.getResources().getDrawable(R.drawable.icon_cellphone);
	    ItemOverlay itemizedoverlay = new ItemOverlay(drawable);
	    projection = mapView.getProjection();
	    mapOverlays.add(new MyOverlay(lat,lon,radius));
	    for (User user : usu){
	    	
	    	la = user.getLatitude()*1E6;
	    	lo = user.getLongitude()*1E6;
	    	GeoPoint point = new GeoPoint(la.intValue(), lo.intValue());

	    	OverlayItem overlayitem = new OverlayItem(point, user.getName(), "");
	    	
	    	mapOverlays.add(itemizedoverlay);
	    	itemizedoverlay.addOverlay(overlayitem);
	    }
	}
	
	private int constroiRaio(){
		int r;
		int x2, y2;
		x2 = lat + radius;
		y2 = lon;
		GeoPoint g1, g2;
		g1 = new GeoPoint(lat, lon);
		g2 = new GeoPoint(x2, y2);
		Projection p = mapView.getProjection();
		Point p1 = new Point(), p2 = new Point();
		p.toPixels(g1, p1);
		p.toPixels(g2, p2);
		r = (int) Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
		return r;
	}
	
	@Override
	protected boolean isRouteDisplayed() {
	    return false;
	}
	
	public class MyOverlay extends Overlay{
    	int lat, lon, radius;
		
    	public MyOverlay(int lat, int lon, int radius){
    		this.lat = lat;
    		this.lon = lon;
    		this.radius = radius;
    	}   
    	
    	public void draw(Canvas canvas, MapView mapv, boolean shadow){
            super.draw(canvas, mapv, shadow);

            Paint mPaint = new Paint();
            mPaint.setDither(true);
            mPaint.setColor(Color.BLUE);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeJoin(Paint.Join.ROUND);
            mPaint.setStrokeCap(Paint.Cap.ROUND);
            mPaint.setStrokeWidth(2);

            GeoPoint gP1 = new GeoPoint(lat,lon);

            Point p1 = new Point();

    		projection.toPixels(gP1, p1);

            canvas.drawCircle(p1.x, p1.y, radius, mPaint);
        }
    }

	
	private class DrawUsersPolling extends TimerTask{
		public void run(){
			drawUsers();
		}
	}
}
